import React, { useMemo, useCallback, useState, useEffect } from 'react';
import { Menu, Breadcrumb, Dropdown, Button } from 'antd';
import { LogoutOutlined } from '@ant-design/icons';
import { useDispatch, history } from 'umi';
import routesArr from '@/routes/routeConfig';
import styles from './index.less';

interface PageHeaderProps {
  userinfo: any;
}

const namespace = 'login';

const PageHeader: React.FC<PageHeaderProps> = ({ userinfo }) => {
  const [pageName, setPageName] = useState<string>('');
  const dispatch = useDispatch();

  const handleLogout = useCallback(() => {
    dispatch({
      type: `${namespace}/requestLogout`,
    });
  }, []);

  const dropMenu = useMemo(
    () => (
      <Menu>
        <Menu.Item key="logout">
          <Button type="text" icon={<LogoutOutlined />} onClick={handleLogout}>
            退出登录
          </Button>
        </Menu.Item>
      </Menu>
    ),
    [],
  );

  useEffect(() => {
    history.listen((path) => {
      routesArr.forEach((item) => {
        if (item.path === history?.location?.pathname) {
          setPageName(item.name);
        }
      });
    });
  }, []);

  return (
    <>
      <div className={styles.header}>
        {Object.keys(userinfo)?.length ? (
          <>
            <div className={styles.avater}>
              <img src={userinfo.avatar_url} />
            </div>
            <Dropdown overlay={dropMenu} placement="bottomLeft" arrow>
              <Button type="text">{userinfo.name}</Button>
            </Dropdown>
          </>
        ) : null}
      </div>
      <div className={styles.breadcrumb}>
        <Breadcrumb>
          <Breadcrumb.Item>首页</Breadcrumb.Item>
          <Breadcrumb.Item>{pageName}</Breadcrumb.Item>
        </Breadcrumb>
      </div>
    </>
  );
};

export default PageHeader;
